package com.example.config;

import com.example.resp.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ResultVo exceptionHandler(MethodArgumentNotValidException ex){
        log.error("服务异常",ex);
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String message = error.getDefaultMessage();
            errors.put(fieldName, message);
        });
        return ResultVo.failure(errors);
    }
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultVo exceptionHandler(Exception e){
        log.error("服务异常",e);
        StackTraceElement stackTrace = e.getStackTrace()[0];
        return ResultVo.failure(e.getClass().getName(),stackTrace);
    }

}